package teaching.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import teaching.mapper.PointMapper;
import teaching.mapper.QuestionMapper;
import teaching.mapper.TagMapper;
import teaching.mapper.UserMapper;
import teaching.pojo.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * Author:20201002983_郑雨蓓
 * Date: 2024/3/13
 * Description:
 */
@Service
public class PointServise extends ServiceImpl<PointMapper, Point> {
    @Resource
    PointMapper pointMapper;
    @Resource
    TagMapper tagMapper;
    @Resource
    QuestionMapper questionMapper;

    public List<Point> getPoint() {
        return pointMapper.getAllPointsWithQuestions();
    }

    public List<Tag> getTag() {
        return tagMapper.getTag();
    }

    public List<Questions> getQuestionByPoint(Long point_id) {
        return questionMapper.SelectByPoint(point_id);
    }

    public List<Questions> showAllQuestions() {
        return questionMapper.allQuestions();
    }

    public List<PointRelation> findRelatedPoints(long pointId) {

//        return pointMapper.findRelatedPoints(pointId);
        List<PointRelation> relations = pointMapper.findRelatedPoints(pointId);

        List<PointRelation> adjustedRelations = new ArrayList<>();
        for (PointRelation relation : relations) {
            // 判断关系对象的point1Id和point2Id是否需要调整
            if (relation.getPoint1Id() == pointId && relation.getPoint2Id() != pointId) {
                // 当relation的point1Id为前端提供的pointId，但point2Id不是时，保持不变
                adjustedRelations.add(relation);
            } else if (relation.getPoint2Id() == pointId) {
                // 当relation的point2Id为前端提供的pointId时，调整关系对象的顺序
                relation.setPoint2Id(relation.getPoint1Id());
                relation.setPoint1Id(pointId);
                adjustedRelations.add(relation);
            }
        }
        // 按照 correlationStrength 进行排序
//        adjustedRelations.sort(Comparator.comparingLong(PointRelation::getCorrelationStrength));
        adjustedRelations.sort(Comparator.comparingLong(PointRelation::getCorrelationStrength).reversed());

        return adjustedRelations;
    }

    public int createQuestion(Questions questions) {
        return questionMapper.insertQuestion(questions);
    }

    public void updateCorrelationStrength(List<PointRelation> relations) {
        for (PointRelation relation : relations) {
            pointMapper.updateCorrelationStrength(relation.getId(), relation.getCorrelationStrength());
        }
    }

    public int createPointRelation(PointRelation pointRelation) {
        return pointMapper.insert(pointRelation);
    }

    public int addPoint(Point point) {
        return pointMapper.addPoint(point);
    }

    public List<Point> getPointByTag(Long tagId) {
        return pointMapper.getPointByTag(tagId);
    }
}
